package models

import (
	"time"
	"github.com/astaxie/beego/orm"
	"strings"
	"strconv"
)

// 文章
type Topic struct {
	Id              int64  `orm:"pk;auto"`
	Uid             int64
	Title           string
	Category        string
	Lables          string
	Content         string `orm:"size(10000)"`
	Attachment      string
	Created         time.Time `orm:"auto_now_add;type(datetime);index"`
	Updated         time.Time `orm:"auto_now;type(datetime);index"`
	Views           int64     `orm:"index"`
	Author          string
	ReplyTime       time.Time `orm:"index"`
	ReplyCount      int64
	ReplyLastUserId int64
	DeleteFlag      int8
}

func AddTopic(title, category, lable, content string) error {
	// 处理标签
	lable = "$" + strings.Join(strings.Split(lable, " "), "#$") + "#"

	o := orm.NewOrm()

	topic := &Topic{
		Title:    title,
		Category: category,
		Lables:   lable,
		Content:  content,
		Created:  time.Now(),
		Updated:  time.Now(),
		ReplyTime:time.Now(),
		DeleteFlag:0,
	}
	_, err := o.Insert(topic)
	if err != nil {
		return err
	}

	// 更新分类统计
	cate := new(Category)
	qs := o.QueryTable("category")
	err = qs.Filter("title", category).One(cate)
	if err == nil {
		// 如果不存在我们就直接忽略，只当分类存在时进行更新
		cate.TopicCount++
		_, err = o.Update(cate)
	}

	return err
}

func GetTopic(tid string) (*Topic, error) {
	tidNum, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		return nil, err
	}

	o := orm.NewOrm()

	topic := new(Topic)

	qs := o.QueryTable("topic")
	err = qs.Filter("id", tidNum).One(topic)
	if err != nil {
		return nil, err
	}

	topic.Views++
	_, err = o.Update(topic)

	topic.Lables = strings.Replace(strings.Replace(topic.Lables, "#", " ", -1), "$", "", -1)
	return topic, nil
}

func ModifyTopic(tid, title, category, lable, content string) error {
	tidNum, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		return err
	}

	lable = "$" + strings.Join(strings.Split(lable, " "), "#$") + "#"

	var oldCate string
	o := orm.NewOrm()
	topic := &Topic{Id: tidNum}
	if o.Read(topic) == nil {
		oldCate = topic.Category
		topic.Title = title
		topic.Category = category
		topic.Lables = lable
		topic.Content = content
		topic.Updated = time.Now()
		_, err = o.Update(topic)
		if err != nil {
			return err
		}
	}

	// 更新分类统计
	if len(oldCate) > 0 {
		cate := new(Category)
		qs := o.QueryTable("category")
		err = qs.Filter("title", oldCate).One(cate)
		if err == nil {
			cate.TopicCount--
			_, err = o.Update(cate)
		}
	}

	cate := new(Category)
	qs := o.QueryTable("category")
	err = qs.Filter("title", category).One(cate)
	if err == nil {
		cate.TopicCount++
		_, err = o.Update(cate)
	}
	return nil
}

func DeleteTopic(tid string) error {
	tidNum, err := strconv.ParseInt(tid, 10, 64)
	if err != nil {
		return err
	}

	o := orm.NewOrm()

	var oldCate string
	topic := &Topic{Id: tidNum}
	if o.Read(topic) == nil {
		oldCate = topic.Category

		if topic.DeleteFlag == 0 {
			topic.DeleteFlag = 1
		} else {
			topic.DeleteFlag = 0
		}
		_, err = o.Update(topic)
		if err != nil {
			return err
		}
	}

	if len(oldCate) > 0 {
		cate := new(Category)
		qs := o.QueryTable("category")
		err2 := qs.Filter("title", topic.Category).One(cate)
		if err2 == nil {
			if topic.DeleteFlag == 0 {
				cate.TopicCount++
			} else {
				cate.TopicCount--
			}

			_, err2 = o.Update(cate)
		}
	}
	return err
}

func GetAllTopics(category, lable string, isDesc bool, page Page) (topics []*Topic, err error) {
	o := orm.NewOrm()

	topics = make([]*Topic, 0)

	qs := o.QueryTable("topic")
	if isDesc {
		if len(category) > 0 {
			qs = qs.Filter("category", category)
		}
		if len(lable) > 0 {
			qs = qs.Filter("lables__contains", "$" + lable + "#")
		}
		//未删除
		qs = qs.Filter("delete_flag", 0)//未删除状态
	}
	_, err = qs.Limit(page.Rows, page.Rows * (page.Page - 1)).OrderBy("-created").All(&topics)

	return topics, err
}
